package com.danbay.cloud.auth.service;

import com.danbay.cloud.account.dto.AccountDto;
import com.danbay.cloud.auth.entity.Account;
import com.danbay.cloud.auth.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author SJG
 *         2017/12/19.
 */
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private AccountMapper accountMapper;

    /**
     * 从账户库取账户信息
     *
     * @param userName 用户名
     * @return UserDetails
     * @throws UsernameNotFoundException 无该用户
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        Account account = accountMapper.selectById(userName);
        if(account==null){
            throw new UsernameNotFoundException("无该账户");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        User user = new User(account.getUserName(), account.getPassword(), authorities);
        return user;
    }

}
